<?php

namespace backend\models;

use backend\base\BaseModel;
use yii\helpers\ArrayHelper;

class AdminRoleModel extends BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin_role';
    }

    public function rules()
    {
        return [
            [['id','status','create_time','organization_id'], 'integer', 'message' => '{attribute}必须整数'],
            [['name'], 'string', 'max' => 64, 'message' => '{attribute}不能超过64字符'],
            [['name'], 'required', 'on' => ['add','edit'], 'message' => '{attribute}不能为空'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => '角色ID',
            'name' => '角色名称',
            'status' => '角色状态',
            'organization_id' => '机构ID',
            'create_time' => '创建时间',
        ];
    }

    /**
     * 保存前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert)){
            if($this->isNewRecord){
                $this->create_time = time();
                $this->status = 1;
                $this->organization_id = isset($this->organization_id) ? $this->organization_id : 0;
            }
            return true;
        }
        return false;
    }

    /**
     * 获取顶级角色
     */
    public static function getRoleList()
    {
        $res = self::find()->select('id,name')->where('status=1')->asArray()->all();
        $res = ArrayHelper::map($res,'id','name');
        return $res;
    }
}